package com.baomidou.ant.service.impl;

import com.baomidou.ant.entity.*;
import com.baomidou.ant.mapper.UserMapper;
import com.baomidou.ant.service.*;
import com.baomidou.ant.utils.Md5Utils;
import com.baomidou.ant.vo.Request.RequestRegisterVo;
import com.baomidou.ant.vo.Request.RequestUserListVo;
import com.baomidou.ant.vo.Response.ResponseUserListVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2021-03-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Value("${file.upload.path}")
    private String uploadPath;
    @Autowired
    private IPveInfoService pveInfoService;
    @Autowired
    private IUserBagService userBagService;
    @Autowired
    private IPvpRecordService pvpRecordService;
    @Autowired
    private IEndlessInfoService endlessInfoService;
    @Autowired
    private IErrorBookService errorBookService;
    @Autowired
    private IDrawPointsService drawPointsService;
    @Autowired
    private IPvpRoomService pvpRoomService;

    @Override
    public User queryByTel(String telephone) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("telephone",telephone);
        return getOne(queryWrapper);
    }

    @Override
    public User queryByName(String userName) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",userName);
        return getOne(queryWrapper);
    }

    @Override
    public void register(RequestRegisterVo requestRegisterVo) {
        User user=new User();
        BeanUtils.copyProperties(requestRegisterVo,user);
        user.setType(false);
        user.setPassword(Md5Utils.hash(requestRegisterVo.getPassword()));
        save(user);
        //为新用户生成相应闯关纪录（初始,纪录为0）
        PveInfo pveInfo=new PveInfo();
        pveInfo.setUserId(user.getId());
        pveInfoService.save(pveInfo);
        //为新用户加载背包
        UserBag userBag=new UserBag();
        userBag.setUserId(user.getId());
        userBagService.save(userBag);
        //为新用户添加pvp战绩
        PvpRecord pvpRecord=new PvpRecord();
        pvpRecord.setUserId(user.getId());
        pvpRecordService.save(pvpRecord);
        //为用户加载无尽数据
        EndlessInfo endlessInfo=new EndlessInfo();
        endlessInfo.setUserId(user.getId());
        endlessInfoService.save(endlessInfo);
        //为用户加入错题本
        ErrorBook errorBook=new ErrorBook();
        errorBook.setUserId(user.getId());
        errorBookService.save(errorBook);
        //为用户加入抽奖积分
        DrawPoints drawPoints=new DrawPoints();
        drawPoints.setUserId(user.getId());
        drawPointsService.save(drawPoints);
        //为用户创建pvp资格
        PvpRoom pvpRoom=new PvpRoom();
        pvpRoom.setUserId(user.getId());
        pvpRoom.setUserName(getById(user.getId()).getUsername());
        pvpRoomService.save(pvpRoom);
    }

    @Override
    public IPage<ResponseUserListVo> userList(RequestUserListVo requestUserListVo) {
        //设置分页对象
        IPage<User> iPage=new Page<>(requestUserListVo.getDisplayStart(),requestUserListVo.getDisplayLength());
        //设置查询条件
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        //判断用户名
        if(StringUtils.isNotEmpty(requestUserListVo.getUsername())){
            queryWrapper.like("username",requestUserListVo.getUsername());
        }
        //判断电话号码
        if(StringUtils.isNotEmpty(requestUserListVo.getTelephone())){
            queryWrapper.like("telephone",requestUserListVo.getTelephone());
        }
        //判断性别
        if(StringUtils.isNotEmpty(requestUserListVo.getSex())){
            queryWrapper.like("sex",requestUserListVo.getSex());
        }
        //判断省份
        if(StringUtils.isNotEmpty(requestUserListVo.getProvince())){
            queryWrapper.like("province",requestUserListVo.getProvince());
        }
        //根据条件查询
        IPage<User> userIPage=page(iPage,queryWrapper);
        if(iPage.getRecords().size()<=0){
            return null;
        }
        return userIPage.convert(user -> {
            ResponseUserListVo responseUserListVo=new ResponseUserListVo();
            BeanUtils.copyProperties(user,responseUserListVo);
            return responseUserListVo;
        });
    }

    @Override
    public String upload(MultipartFile file) {
        // 获取上传文件名
        String filename = file.getOriginalFilename();
        // 定义上传文件保存路径
        String path = uploadPath+"userImages/";
        // 新建文件
        File filepath = new File(path, filename);
        // 判断路径是否存在，如果不存在就创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        try {
            file.transferTo(new File(path + File.separator + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "userImages/"+ filename;
    }


}
